package com.flashcash.solu.common;

import android.content.Context;
import android.content.SharedPreferences;

import com.flashcash.solu.app.App;
import com.flashcash.solu.bean.LatestLoanAppBean;
import com.flashcash.solu.bean.LoginStatusBean;
import com.flashcash.solu.enums.LoginStatusEnum;
import com.hwangjr.rxbus.RxBus;
import com.x.leo.apphelper.data.cache.CacheDataManage;

import org.jetbrains.annotations.NotNull;

import java.util.Map;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class TokenManager {


    public static String MOBILE_CACHE_KEY = "mobile_cache_key";
    public static String TOKEN_CACHE_KEY = "token_cache_key";
    public static String TOKEN_CACHE_TIME = "token_cache_time";
    public static String REFRESH_TOKEN_CACHE_KEY = "refresh_token_cache_key";
    public static String REFRESH_TOKEN_CACHE_TIME = "refresh_token_cache_time";

    public static boolean isExpired = false;
    public static boolean isReSetLoanStatus = false;
    public long mLoginTime;
    private LoginStatusBean mLoginStatus;

    public Map<String, Object> mTempStatus;

    SharedPreferences cache;

    public static TokenManager getInstance() {
        return Holder.INSTANCE;
    }

    public void setMobile(String mobile) {
        if (!mobile.startsWith("0")) {
            mobile = "0" + mobile;
        }
        cache.edit().putString(MOBILE_CACHE_KEY, mobile).apply();
    }

    public String getMobile() {
        return cache.getString(MOBILE_CACHE_KEY, null);
    }

    public void setToken(String token, int time) {
        if (time <= 0) {
            cache.edit().putString(TOKEN_CACHE_KEY, token).putInt(TOKEN_CACHE_TIME, 0).apply();
        } else {
            cache.edit().putString(TOKEN_CACHE_KEY, token).putInt(TOKEN_CACHE_TIME, time).apply();
        }
        long l = System.currentTimeMillis();
        mLoginStatus.mChangTime = l;
        mLoginTime = l;
        mLoginStatus.mLoginStatus = LoginStatusEnum.UNLOGIN_LOGIN;
        isExpired = false;

    }

    public void setRefreshToken(String refreshToken, int time) {

        if (time <= 0) {
            cache.edit().putString(REFRESH_TOKEN_CACHE_KEY, refreshToken).putInt(REFRESH_TOKEN_CACHE_TIME, 0).apply();
        } else {
            cache.edit().putString(REFRESH_TOKEN_CACHE_KEY, refreshToken).putInt(REFRESH_TOKEN_CACHE_TIME, time).apply();
        }
    }

    public String getToken() {
        return cache.getString(TOKEN_CACHE_KEY, null);
    }

    public String getRefreshToken() {
        return cache.getString(REFRESH_TOKEN_CACHE_KEY, null);
    }

    private TokenManager() {
        cache = App.instance.getSharedPreferences("CACHE_FILE", Context.MODE_PRIVATE);
        mLoginStatus = new LoginStatusBean();

    }

    /**
     * 检查登录状态是否变化，确定是否需要更新界面
     *
     * @param lastUpdateTime 上次获取状态时间
     * @return
     */
    public boolean isLoginStateChange(long lastUpdateTime) {
        return mLoginStatus.mChangTime > lastUpdateTime;
    }

    /**
     * 获取具体变化方式
     *
     * @return
     */
    public LoginStatusEnum getLoginStateChange() {
        return mLoginStatus.mLoginStatus;
    }

    public void addToNextPull(@NotNull Function1<? super LatestLoanAppBean, Unit> block) {
        block.invoke(new LatestLoanAppBean());
    }

    public void requestLatestLoanData(@NotNull Function1<? super LatestLoanAppBean, Unit> block) {
        block.invoke(new LatestLoanAppBean());
    }


    public static void storeYWAccount(String userid, String password) {
        CacheDataManage.INSTANCE.addData(FieldParamsInt.YW_ACCOUNT_PASSWORD, password);
        CacheDataManage.INSTANCE.addData(FieldParamsInt.YW_ACCOUNT_USERID, userid + Holder.INSTANCE.getMobile());
    }

    public static String getYWAccountID() {
        String s = CacheDataManage.INSTANCE.obtainData(FieldParamsInt.YW_ACCOUNT_USERID, String.class);
        if (s != null && s.contains(getInstance().getMobile())) {
            return s.replace(getInstance().getMobile(), "");
        }
        return null;
    }

    private static class Holder {
        private static final TokenManager INSTANCE = new TokenManager();
    }

    Subscription subscription;

    /**
     * 需要重新登录
     */
    public void refreshTokeExpired() {
        clear();
        subscription =
                Observable.just(1)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<Integer>() {
                            @Override
                            public void call(Integer integer) {
                                RxBus.get().post(new TokenExpiredEvent());
                                if (subscription != null && !subscription.isUnsubscribed()) {
                                    subscription.unsubscribe();
                                }
                            }
                        });
    }

    public void clear() {
        cache.edit().clear().apply();
        mLoginStatus.mChangTime = System.currentTimeMillis();
        mLoginStatus.mLoginStatus = LoginStatusEnum.LOGIN_LOGOUT;
    }

    public boolean hasLogin() {
        return getToken() != null && !isExpired;
    }

    public static class TokenExpiredEvent {
    }
}
